﻿using System;
using System.Linq;
using System.Web.Mvc;
using Yonkly.Models;
using Yonkly.Services;
using Yonkly.Utility;
using Membership = System.Web.Security.Membership;

namespace Yonkly.Controllers
{
    public class ProfileController : BaseController
    {
        public ActionResult Edit()
        {
            if (IsUserAuthenticated)
                return View("Edit", GetProfileViewData());
            else
                return Redirect("~/");
        }

        public ActionResult UpdateTwitter(string userName, string password)
        {
            var result = new Yonkly.Models.JsonResult();
            if (!IsUserAuthenticated)
            {
                //should not happen
                return Redirect("~/");
            }
            if (string.IsNullOrEmpty(userName))
            {
                //delete twitter integration
                using (var dc = new YonklyDataContext())
                {
                    var settings = GetUserSettings(dc, LoggedInUserId);
                    settings.TwitterUserName = null;
                    settings.TwitterPassword = null;

                    dc.SubmitChanges();
                }
                result.isSuccessful = true;
            }
            else
            {
                if (string.IsNullOrEmpty(password))
                {
                    result.isSuccessful = false;
                    result.errorMessage = "Password cannot be blank.";
                }
                else
                {
                    //authenticate with twitter
                    Twitter tw = new Twitter();
                    if (!tw.VerifyCredentials(userName, password))
                    {
                        result.isSuccessful = false;
                        result.errorMessage = "Twitter authentication failed";
                    }
                    else
                    {
                        try
                        {
                            using (var dc = new YonklyDataContext())
                            {
                                var settings = GetUserSettings(dc, LoggedInUserId);
                                settings.TwitterUserName = userName;
                                settings.TwitterPassword = password;

                                dc.SubmitChanges();
                            }
                            result.isSuccessful = true;
                        }
                        catch (Exception)
                        {
                            result.isSuccessful = false;
                            result.errorMessage = "Failed to save twitter information";
                        }
                    }
                }
            }

            return View("Json", result);
        }

        public ActionResult Update(string email, string url, string about, string name, bool emailOnFollow, bool emailOnResponse)
        {
            var result = new Yonkly.Models.JsonResult();
            if (!IsUserAuthenticated)
            {
                //should not happen
               return Redirect("~/");
            }
            if (string.IsNullOrEmpty(email))
            {
                result.isSuccessful = false;
                result.errorMessage = "Email cannot be blank.";
            }
            else if (!Globals.IsValidEmail(email))
            {
                result.isSuccessful = false;
                result.errorMessage = "Invalid email address.";
            }
            else
            {
                try
                {
                    var curUser = Membership.GetUser();
                    curUser.Email = email;
                    Membership.UpdateUser(curUser);
                    using (var dc = new YonklyDataContext())
                    {
                        var settings = GetUserSettings(dc, LoggedInUserId);
                        settings.Name = name;
                        settings.About = about;
                        settings.Url = url;
                        settings.ReceiveEmailOnFollow = emailOnFollow;
                        settings.ReceiveEmailOnResponse = emailOnResponse;

                        dc.SubmitChanges();
                    }
                    result.isSuccessful = true;
                }
                catch
                {
                    result.isSuccessful = false;
                    result.errorMessage = "Failed to save changes";
                }
            }
            return View("Json", result);
        }

        public ActionResult ChangePassword(string oldPassword, string newPassword)
        {
            var result = new Yonkly.Models.JsonResult();
            if (!IsUserAuthenticated)
            {
                //should not happen
                return Redirect("~/");
            }
            if (string.IsNullOrEmpty(newPassword))
            {
                result.errorMessage = "Password cannot be blank.";
            }
            else if (newPassword.Length < UserManager.MinRequiredPasswordLength)
            {
                result.errorMessage = string.Format("Password must be {0} character long.",
                                                    UserManager.MinRequiredPasswordLength);
            }
            else
            {
                var status = Membership.GetUser().ChangePassword(oldPassword, newPassword);
                result.isSuccessful = status;
                if (!status)
                {
                    result.errorMessage = "Failed to change your password.";
                }
            }
            return View("Json", result);
        }
        
        [NonAction]
        public static UserSetting GetUserSettings(Guid userid)
        {
            using (var dc = new YonklyDataContext())
            {
                var query = dc.UserSettings.Where(us => us.UserId == userid);
                if (query.Count() == 0)
                {
                    //create the settings row
                    var us = new UserSetting();
                    us.UserId = userid;
                    us.ReceiveEmailOnFollow = true;
                    us.ReceiveSMS = false;
                    us.ReceiveEmails = true;
                    dc.UserSettings.InsertOnSubmit(us);
                    dc.SubmitChanges();
                }
                return query.First();
            }
        }

        [NonAction]
        public static UserSetting GetUserSettings(YonklyDataContext dc, Guid userid)
        {
            var query = dc.UserSettings.Where(us => us.UserId == userid);
            if (query.Count() == 0)
            {
                //create the settings row
                var us = new UserSetting();
                us.UserId = userid;
                us.ReceiveEmailOnFollow = true;
                us.ReceiveSMS = false;
                us.ReceiveEmails = true;
                us.TwitterUserName = null;
                us.TwitterPassword = null;
                dc.UserSettings.InsertOnSubmit(us);
                dc.SubmitChanges();
            }
            return query.First();
        }

        [NonAction]
        private ProfileViewData GetProfileViewData()
        {
            var vd = new ProfileViewData(GetBaseViewData());
            var settings = GetUserSettings(LoggedInUserId);
            vd.ReceiveEmailOnFollow = settings.ReceiveEmailOnFollow;
            vd.ReceiveEmailOnResponse = settings.ReceiveEmailOnResponse;
            vd.About = settings.About ?? string.Empty;
            vd.Name = settings.Name ?? string.Empty;
            vd.Url = settings.Url ?? string.Empty;
            vd.TwitterUserName = settings.TwitterUserName;
            vd.TwitterPassword = settings.TwitterPassword;
            return vd;
        }
    }
}